package com.tim.source.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlDomProc {
	private static DocumentBuilderFactory factory;
	private static DocumentBuilder builder;
	static {
		XmlDomProc.factory = DocumentBuilderFactory.newInstance();
		try {
			XmlDomProc.builder = XmlDomProc.factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 依据输入流转化Document.
	 * 
	 * @param InputStream
	 *            input.
	 * @return Document Document.
	 */
	public static Document getDocument(InputStream input) {
		try {
			return XmlDomProc.builder.parse(input);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 创建Xml文件并写入信息.
	 * 
	 * @param fileName
	 *            文件地址.
	 * @param charset
	 *            编码字符集.
	 */
	public void createXml(String fileName, String charset) {
		Document document = XmlDomProc.builder.newDocument();
		Element root = document.createElement("employees");
		document.appendChild(root);
		Element employee = document.createElement("employee");
		Element name = document.createElement("name");
		name.appendChild(document.createTextNode("丁宏亮"));
		employee.appendChild(name);
		Element sex = document.createElement("sex");
		sex.appendChild(document.createTextNode("m"));
		employee.appendChild(sex);
		Element age = document.createElement("age");
		age.appendChild(document.createTextNode("30"));
		employee.appendChild(age);
		root.appendChild(employee);
		docToXmlFile(document, charset, fileName);
	}

	/**
	 * dom对象转化Xml.
	 * 
	 * @param document
	 *            Document.
	 * @param charset
	 *            字符集.
	 * @param fileName
	 *            保存文件路径.
	 * @return boolean
	 */
	public boolean docToXmlFile(Document document, String charset,
			String fileName) {
		try {
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			transformer.setOutputProperty(OutputKeys.ENCODING, charset);
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			DOMSource source = new DOMSource(document);
			File file = new File(fileName);
			file.createNewFile();
			PrintWriter writer = new PrintWriter(new FileOutputStream(fileName));
			StreamResult result = new StreamResult(writer);
			transformer.transform(source, result);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public void parserXml(String fileName) {
		try {
			Document document = XmlDomProc.builder.parse(fileName);
			NodeList employees = document.getChildNodes();
			for (int i = 0; i < employees.getLength(); i++) {
				Node employee = employees.item(i);
				NodeList employeeInfo = employee.getChildNodes();
				for (int j = 0; j < employeeInfo.getLength(); j++) {
					Node node = employeeInfo.item(j);
					NodeList employeeMeta = node.getChildNodes();
					for (int k = 0; k < employeeMeta.getLength(); k++) {
						System.out.println(employeeMeta.item(k).getNodeName()
								+ ":" + employeeMeta.item(k).getTextContent());
					}
				}
			}
			System.out.println("解析完毕");
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
		} catch (SAXException e) {
			System.out.println(e.getMessage());
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
}
